package com.tutou.ikuser.hander;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tutou.ikuser.pojo.dto.Result;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * BadCredentialsException：用户名或密码错误。
     * UsernameNotFoundException：未找到指定用户名。
     * LockedException：账户被锁定。
     * DisabledException：账户被禁用。
     * AccountExpiredException：账户过期。
     * CredentialsExpiredException：凭据（密码）过期。
     * InsufficientAuthenticationException：未提供足够的认证信息。
     * SessionAuthenticationException：会话（Session）认证异常，如并发登录限制等。
     */

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        if (authException instanceof BadCredentialsException) {
            response.getWriter().write(objectMapper.writeValueAsString(Result.fail("用户名或密码错误~")));
        } else if (authException instanceof UsernameNotFoundException) {
            response.getWriter().write(objectMapper.writeValueAsString(Result.fail("用户不存在~")));
        } else if (authException instanceof InsufficientAuthenticationException) {
            response.getWriter().write(objectMapper.writeValueAsString(Result.fail("请登录~")));
        }
    }
}
